﻿using Models.Common;
using Models.MVC;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Web.Filters;

namespace Web.Controllers.MVC
{
    [MvcAuthentication]
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            ViewBag.UserName = Common.CookiesManagement.GetUserModel().UserName;
            return View();
        }
        public ActionResult Starer()
        {
            ViewBag.UserName = Common.CookiesManagement.GetUserModel().UserName;
            return View();
        }

        public string Init()
        {
            var info = Web.Common.Common.GetInitInfoModel();
            return Newtonsoft.Json.JsonConvert.SerializeObject(info);
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login()
        {
            FormsAuthentication.SignOut();
            return View();
        }
        [HttpPost, AllowAnonymous]
        public ActionResult LoginAsync(UsersModel User, int RememberMe = 0)
        {
            Models.Common.Result<string> result = new Models.Common.Result<string>();
            //if (Captcha.ToUpper() != Session["Captcha"].ToString().ToUpper())
            //{
            //    result.Type = AjaxResultType.Error;
            //    result.Content = "验证码错误";
            //}
            //DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query("select Logins.LoginPass,Logins.UserID,Users.UserName from Logins inner join Users on Logins.UserID=Users.ID where Logins.LoginType=1 and Logins.LoginName='" + LoginName + "' and Logins.IsDeleted=0 and Users.IsDeleted=0").Tables[0];
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query("select Logins.*,Users.* from Logins full join Users on Logins.ID=Users.ID or LoginName ='" + User.LoginName + "' ").Tables[0];
            if (dt.Rows.Count != 1)
            {
                result.Type = Models.Common.AjaxResultType.Error;
                result.Content = "登录名错误";
            }
            else if (dt.Rows[0]["LoginPass"].ToString() != User.LoginPass)
            {
                result.Type = Models.Common.AjaxResultType.Error;
                result.Content = "密码错误";
            }
            else
            {
                Models.Common.CookiesUserModel m = new CookiesUserModel();
                m.LoginName = User.LoginName;
                m.UserID = Convert.ToInt32(dt.Rows[0]["ID"]);
                m.UserName = Convert.ToString(dt.Rows[0]["UserName"]);
                result.Type = AjaxResultType.Success;
                result.Content = "登录成功";
                var data = Newtonsoft.Json.JsonConvert.SerializeObject(m);
                var ticket = new FormsAuthenticationTicket(
                                    1,
                                    User.LoginName,
                                    DateTime.Now,
                                    DateTime.Now.Add(FormsAuthentication.Timeout),
                                    RememberMe == 1 ? true : false,
                                    data);
                var cookie = new HttpCookie(
                    FormsAuthentication.FormsCookieName,
                    FormsAuthentication.Encrypt(ticket));
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);
            }
            return Json(result);
        }

        public ActionResult GoodsList()
        {
            return View();
        }
        [HttpPost]
        public string GoodsListAsync(int PageIndex=1,int PageSize=20,string Search="")
        {
            GridResult result = new GridResult();
            SqlParameter[] parameters = {
                                            new SqlParameter("@PageIndex",SqlDbType.Int),
                                            new SqlParameter("@PageSize",SqlDbType.Int),
                                            new SqlParameter("@Search",SqlDbType.NVarChar,40000)};
            parameters[0].Value = PageIndex;
            parameters[1].Value = PageSize;
            parameters[2].Value = Search;
            DataSet ds = FreeADO.DBUtility.DbHelperSQL.RunProcedure("SP_QueryGoodsList", parameters, "aaa", 3000);
            result.count = Convert.ToInt32(ds.Tables[0].Rows[0]["count"]);
            result.data = ds.Tables[1];
            result.totalRow = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[2]))[0];
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }

        public ActionResult ImagesList()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public string ImagesListAsync(int PageIndex=1,int PageSize=20,int GroupID=0,int ItemID=0,string FileType="img")
        {
            GridResult result = new GridResult();
            SqlParameter[] parameters = {
                                            new SqlParameter("@PageIndex",SqlDbType.Int),
                                            new SqlParameter("@PageSize",SqlDbType.Int),
                                            new SqlParameter("@GroupID",SqlDbType.Int),
                                            new SqlParameter("@ItemID",SqlDbType.Int),
                                            new SqlParameter("@FileType",SqlDbType.NVarChar,4000)};
            parameters[0].Value = PageIndex;
            parameters[1].Value = PageSize;
            parameters[2].Value = GroupID;
            parameters[3].Value = ItemID;
            parameters[4].Value = FileType;
            DataSet ds = FreeADO.DBUtility.DbHelperSQL.RunProcedure("SP_QueryFilesList", parameters, "aaa", 3000);
            result.count = Convert.ToInt32(ds.Tables[0].Rows[0]["count"]);
            result.data = ds.Tables[1];
            result.totalRow = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[2]))[0];
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }
        public ActionResult ImagesUpload()
        {
            return View();
        }
        [HttpPost]
        public JsonResult UploadPicture()
        {
            return upFile(this);
        }

        public JsonResult upFile(Controller cxt)
        {
            try
            {
                var uploadpath = Server.MapPath("/Upload/");
                var uploadFile = cxt.Request.Files[0];
                var oldName = uploadFile.FileName;
                if (!Directory.Exists(uploadpath))
                {
                    Directory.CreateDirectory(uploadpath);
                }
                var fileName = Guid.NewGuid().ToString() + uploadFile.FileName.Substring((uploadFile.FileName.LastIndexOf('.')), (uploadFile.FileName.Length - uploadFile.FileName.LastIndexOf('.')));
                uploadFile.SaveAs(uploadpath + fileName);
                return Json(new { Code = 0, Message = "上传成功！" });
            }
            catch (Exception ex)
            {
                return Json(new { Code = 1001, Message = "上传失败！" + ex.Message });
            }
        }
    }
}